<template>
<div class="picker-item">
  <span @click="showBlank">
    <span>{{ pickerValue }}</span>
    <van-icon name="play" class="trans"/>
  </span>
  <van-popup v-model="showPicker" position="bottom">
    <van-picker show-toolbar :columns="columns" @confirm="onConfirm" @cancel="showPicker = false"/>
  </van-popup>
</div>
</template>

<script>
export default {
  props: [ 'label', 'value', 'placeholder', 'option', 'readonly' ],
  data() {
    return {
      pickerValue: '',
      showPicker: false,
    } 
  },
  watch: {
    value() {
      if (this.value || this.value === 0) {
        let item = this.option.find(item => item.value === this.value);
        if (item) {
          this.pickerValue = item.label;
          return ;
        }
      }
      this.pickerValue = '';
    },
    option() {
      if (this.value || this.value === 0) {
        let item = this.option.find(item => item.value === this.value);
        if (item) {
          this.pickerValue = item.label;
          return ;
        }
      }
      this.pickerValue = '';
    }
  },
  computed: {
    columns() {
      return this.option.map(item => item.label);
    }
  },
  methods: {
    onConfirm(label, index) {
      if (this.option[index].value === this.value) {
        this.showPicker = false;
        return ;
      }
      this.pickerValue = label;
      this.$emit('input', this.option[index].value);
      this.$emit('change', this.option[index].value);
      this.showPicker = false;
    },
    showBlank() {
      if (this.readonly) return ;
      this.showPicker = true;
    }
  },
  mounted() {
    if (this.value || this.value === 0) {
      let item = this.option.find(item => item.value === this.value);
      if (item) {
        this.pickerValue = item.label;
      }
    }
  }
}
</script>

<style lang="less">
.picker-item {
  font-size: 12px;
  line-height: 0.8rem;
  color: #000;
  margin-right: 0.4rem;
  .trans {
    transform: rotate(90deg);
    transform-origin: 50% 35%;
    margin-left: 3px;
  }
}
</style>
